<template>
  <FormItem v-bind="formItemProps" :rules="computeRules" :disabled="inputDisabled">
    <template #default>
      <InputNumber
        class="form-input-number"
        :value="value !== null && value !== '' ? value : undefined"
        :controls="controls"
        :precision="precision"
        :max="max"
        :min="min"
        :placeholder="computePlaceholder"
        :disabled="inputDisabled"
        v-bind="inputProps"
        v-on="listeners"
        @input="val => $emit('input', val)">
        <template #append>
          <slot name="append"></slot>
        </template>
        <template #prefix>
          <slot name="prefix"></slot>
        </template>
        <template #prepend>
          <slot name="prepend"></slot>
        </template>
        <template #suffix>
          <slot name="suffix"></slot>
        </template>
      </InputNumber>
    </template>
    <template #error="{ error }">
      <slot name="error" :error="error"></slot>
    </template>
    <template #label>
      <slot name="label"></slot>
    </template>
  </FormItem>
</template>

<script>
  import formInput from './form-input'
  import { InputNumber } from '@web-utils/component'
  import { filterProperties, normalizeProps } from '@/util'

  let props = {}
  const mixins = InputNumber.mixins
  if (mixins) {
    ;[...mixins, InputNumber].forEach(value => {
      if (value.props) {
        props = { ...props, ...value.props }
      }
    })
  }

  const autoBindKeys = Object.keys(props).filter(
    key => !['value', 'placeholder', 'disabled', 'precision', 'max', 'min'].includes(key)
  )

  export default {
    name: 'FormInputNumber',
    mixins: [formInput],
    props: {
      value: [Number, String],
      max: {
        type: Number,
        default: Infinity
      },
      min: {
        type: Number,
        default: -Infinity
      },
      precision: {
        type: Number,
        validator(val) {
          return val >= 0 && val === parseInt(val, 10)
        }
      },
      controls: Boolean
    },
    computed: {
      inputProps() {
        return filterProperties({ ...normalizeProps(this.$attrs), ...this.$props }, autoBindKeys)
      }
    }
  }
</script>

<style lang="scss">
  .form-input-number {
    &.el-input-number--mini {
      line-height: 28px;
    }

    &.el-input-number {
      width: 100%;

      .el-input__inner {
        text-align: left;
      }
    }
  }
</style>
